package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysCompany;
import com.ruoyi.system.service.*;
import net.bytebuddy.implementation.bind.annotation.Default;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/product")
public class SysProductController extends BaseController
{
    @Autowired
    private ISysProductService productService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPurposeService purposeService;

    String t = "";

    /**
     * 获取产品列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysProduct product)
    {
/*        SysProduct product = productDetail.getProduct();*/

        startPage();
        List<SysProduct> list = productService.selectProductList(product);
        String productPost = product.getProductPost();
        String productPurpose = product.getProductPurpose();
        if (productPost != null && !productPost.isEmpty()) {
            // 过滤掉postNames中不包含productPost的SysProduct对象
            list = list.stream()
                    .filter(sysProduct -> sysProduct.getPostNames().contains(productPost))
                    .collect(Collectors.toList());
        }
        if (productPurpose != null && !productPurpose.isEmpty()) {
            // 过滤掉postNames中不包含productPost的SysProduct对象
            list = list.stream()
                    .filter(sysProduct -> sysProduct.getPurposeNames().contains(productPurpose))
                    .collect(Collectors.toList());
        }

        return getDataTable(list);
    }

    @Log(title = "产品管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:product:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysProduct product)
    {
        List<SysProduct> list = productService.selectProductList(product);
        ExcelUtil<SysProduct> util = new ExcelUtil<SysProduct>(SysProduct.class);
        util.exportExcel(response, list, "产品数据");
    }

    @Log(title = "产品管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:product:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysProduct> util = new ExcelUtil<SysProduct>(SysProduct.class);
        List<SysProduct> productList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = productService.importProduct(productList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysProduct> util = new ExcelUtil<SysProduct>(SysProduct.class);
        util.importTemplateExcel(response, "产品数据");
    }

    /**
     * 根据产品编号获取详细信息
     */
/*    @PreAuthorize("@ss.hasPermi('system:product:query')")*/
    @GetMapping(value = { "/", "/{productId}" })
    public AjaxResult getInfo(@PathVariable(value = "productId", required = false) Long productId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(productId))
        {
            SysProduct SysProduct = productService.selectProductById(productId);
            ajax.put(AjaxResult.DATA_TAG, SysProduct);
            ajax.put("postIds", postService.selectPostListByProductId(productId));
            ajax.put("purposeIds", purposeService.selectPurposeListByProductId(productId));
        }
        ajax.put("posts", postService.selectPostAll());
        ajax.put("purposes", purposeService.selectPurposeAll());
        return ajax;
    }

    /**
     * 新增产品
     */
    @PreAuthorize("@ss.hasPermi('system:product:add')")
    @Log(title = "产品管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysProduct product)
    {
        deptService.checkDeptDataScope(product.getDeptId());
        if (!productService.checkProductNameUnique(product))
        {
            return error("新增产品'" + product.getProductName() + "'失败，产品已存在");
        }
        product.setAvatar(t);
        product.setCreateBy(getUsername());
        return toAjax(productService.insertProduct(product));
    }

    /**
     * 修改产品
     */
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @Log(title = "产品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysProduct product)
    {
        deptService.checkDeptDataScope(product.getDeptId());
        if (!productService.checkProductNameUnique(product))
        {
            return error("修改产品'" + product.getProductName() + "'失败，产品已存在");
        }
        product.setAvatar(t);
        product.setUpdateBy(getUsername());
        return toAjax(productService.updateProduct(product));
    }

    /**
     * 删除产品
     */
    @PreAuthorize("@ss.hasPermi('system:product:remove')")
    @Log(title = "产品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable Long[] productIds)
    {
        if (ArrayUtils.contains(productIds, getUserId()))
        {
            return error("当前产品不能删除");
        }
        return toAjax(productService.deleteProductByIds(productIds));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @Log(title = "产品管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysProduct product)
    {
        product.setUpdateBy(getUsername());
        return toAjax(productService.updateProductStatus(product));
    }


    /**
     * 获取材质树列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }


    /**
     * 图片上传
     */
    @Log(title = "产品图片", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
//            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
//            if (productService.updateProductAvatar(loginUser.getUsername(), avatar))
//            {
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", avatar);
//                // 更新缓存用户头像
//                loginUser.getUser().setAvatar(avatar);
//                return ajax;
//            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("productImageUrl", avatar);
            t = avatar;
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }

    @GetMapping("/select")
    public AjaxResult select()
    {
        List<SysProduct> sys = productService.selectAll();

        return AjaxResult.success(sys);
    }


    @GetMapping("/getImage")
    public AjaxResult getImage(
                                String color,
                               String productPost,
                               String deptName
    )
    {
        SysProduct product = new SysProduct();
        product.setProductPost(productPost);
        product.setColor(color);
        product.getDept().setDeptName(deptName);
        List<SysProduct> list = productService.selectProductList(product);

        String productPost1 = product.getProductPost();
        if (productPost1 != null && !productPost1.isEmpty()) {
            // 过滤掉postNames中不包含productPost的SysProduct对象
            list = list.stream()
                    .filter(sysProduct -> sysProduct.getPostNames().contains(productPost1))
                    .collect(Collectors.toList());
        }
        String deptName1 = product.getDept().getDeptName();
        if (deptName1 != null && !deptName1.isEmpty()) {
            list = list.stream()
                    .filter(sysProduct -> sysProduct.getDept().getDeptName().contains(deptName1))
                    .collect(Collectors.toList());
        }
        return AjaxResult.success(list);
    }
}
